/**
 * editor_plugin_src.js
 *
 * Copyright 2013, Imagine.lt studio
 * Released under LGPL License.
 *
 */

(function() {
	tinymce.create('tinymce.plugins.AdvancedFilePlugin', {
		init : function(ed, url) {
			// Register commands
			ed.addCommand('mceFile', function() { 
			
				var anySelection = false;
				var focusElm = ed.selection.getNode();
				var selectedText = ed.selection.getContent({format:'text'});
				
				
				if (ed.selection.getNode())
					anySelection = (ed.selection.getNode().nodeName.toLowerCase() == "img") || (selectedText && selectedText.length > 0);

				if (anySelection || (focusElm != null && focusElm.nodeName == "A")) {
				
					// Internal image object like a flash placeholder
					if (ed.dom.getAttrib(ed.selection.getNode(), 'class', '').indexOf('mceItem') != -1)
						return;
						
					var tvs_parent = ed.getParam("tvs_parent");
					var tvs_tpl_parent_name = ed.getParam("tvs_tpl_parent_name");
					var tvs_field = ed.getParam("tvs_field");
					
					ed.windowManager.open({
						file : ed.documentBaseURI.getURI(url)+'index.php?admin=1&insfil=1&parent='+tvs_parent+'&tpl_parent_name='+tvs_tpl_parent_name+'&field='+tvs_field,
						//file : url + '/image.htm',
						width : 620 + parseInt(ed.getLang('file.delta_width', 0)),
						height : 540 + parseInt(ed.getLang('file.delta_height', 0)),
						inline : 1
					}, {
						plugin_url : url
					});
				
				}
				
				
			});

			// Register buttons
			ed.addButton('file', {
				title : 'advfile.file_desc',
				cmd : 'mceFile'
				//image : url + '/img/file.gif'
			});
			
			ed.onNodeChange.add(function(ed, cm, n, co) {
				cm.setDisabled('file', co && n.nodeName != 'A');
				cm.setActive('file', n.nodeName == 'A' && !n.name);
			});
		},

		getInfo : function() {
			return {
				longname : 'Advanced files',
				author : 'Imagine Team',
				authorurl : 'http://www.imagine.lt',
				infourl : 'http://www.imagine.lt',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('file', tinymce.plugins.AdvancedFilePlugin);
})();